import {ajaxUtils, strUtils} from "@/utils/lwUtils";
import {getToken, removeToken, setToken} from "@/utils/auth";
import {apiGetUser, apiGrSsoLogin, apiWxSsoLogin} from "@/api/user";
import Router from "@/router";
import {Dialog} from "vant";
import eraqDlg from "../utils/dialog";

let ssoConstants = {
    ak: "BCDSGA_8296367e54435f70d99226597861a6d6",
    loginUrl: {
        gr: "https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1",
        fr: "https://esso.zjzwfw.gov.cn/opensso/spsaehandler/metaAlias/sp",
        irs: "https://portal.zjzwfw.gov.cn/uc/sso/login?appId=2001700221",
        wx: "",
        ali: "https://puser.zjzwfw.gov.cn/sso/alipay.do?action=ssoLogin",
    },
    //单点登录后，接收单点登录ticket或ssotoken的地址
    backUrl: "http://qyda.scjgj.zjtz.gov.cn:8088/eraq-api/api/user/sso/mb/login",
    homeUrl: "https://mapi.zjzwfw.gov.cn/web/mgop/gov-open/zj/2001700221/reserved/index.html",
}

//获取ticket完成单点登录认证，若无该参数，则发起单点登录
function doSsoGrLogin(ticket) {
    apiGrSsoLogin(ticket).then(res => {
        if (ajaxUtils.isFail(res.code, res.msg)) {
            showErr("用户ticket已过期，请返回浙里办重新登录");
            return;
        }
        setToken(res.data);
    }).catch(() => {
    });
}

//接收微信端发送的ticketId，完成单点登录认证
function doSsoWxLogin(ticketId) {
    if (ticketId !== "") {
        reqToken(ticketId);
        return;
    }
    //当“浙里办”单点登录失败或登录态失效时调用 ZWJSBridge.openLink 方法重新获取ticketId。
    ZWJSBridge.openLink({type: "reload"}).then(res => {
        reqToken(res.ticketId);
    }).catch(() => {
        showErr("获取用户ticketId异常");
    });
}

//通过ticketId请求登录用户信息
function reqToken(ticketId) {
    if (strUtils.isEmpty(ticketId)) {
        showErr("未检测到用户ticketId，请返回浙里办重新登录");
        return;
    }
    apiWxSsoLogin(ticketId).then(res => {
        if (ajaxUtils.isFail(res.code, res.msg)) {
            showErr("用户ticketId检验失败，请返回浙里办重新登录");
            return;
        }
        setToken(res.data);
    }).catch(() => {
    });
}

function ssoGrUrl() {
    let gotoUrl = strUtils.getUrlParam("goto");
    return ssoConstants.loginUrl.gr + "&servicecode=" + ssoConstants.ak + "&goto=" + gotoUrl;
}

function ssoFrUrl() {
    let gotoUrl = strUtils.getUrlParam("goto");
    return ssoConstants.loginUrl.fr + "?spappurl=" + ssoConstants.backUrl + "?goto=" + gotoUrl;
}

function ssoIrsUrl() {
    return ssoConstants.loginUrl.irs + "&sp=" + ssoConstants.homeUrl;
}

function ssoAliUrl() {
    let gotoUrl = strUtils.getUrlParam("goto");
    return ssoConstants.loginUrl.ali + "&servicecode=" + ssoConstants.ak + "&goto=" + gotoUrl;
}

function showErr(errMsg) {
    Router.push({path: "/index", query: {errCode: 500, errMsg}});
}

//导出对外提供的方法
const ssoUtil = {
    doSsoLogin: function () {
        //URL中含有token(—法人登录后返回)----以该token为准，写入本地缓存，校验用户有效性
        let token = strUtils.getUrlParam("token");
        if (!strUtils.isEmpty(token)) {
            setToken(token);
        }

        //检测缓存中的token，并校验
        token = getToken();
        if (!strUtils.isEmpty(token)) {
            apiGetUser().then(res => {
                if (!ajaxUtils.isFail(res.code, res.msg)) {
                    return;
                }
                token = "";
                removeToken();
            }).catch(() => {
                token = "";
                removeToken();
            });
        }

        //校验失败或本地缓存中不存在token，则检测登录的ticketId
        if (token !== "") {
            return;
        }

        //检测个人单点登录tiket
        /*let ticket = strUtils.getUrlParam("ticket");
        if (!strUtils.isEmpty(ticket)) {
            doSsoGrLogin(ticket);
            return;
        }*/

        //对接浙里办IRS方式登录
        let ticketId = strUtils.getUrlParam("ticketId");
        if (ticketId !== "") {
            reqToken(ticketId);
            return;
        }

        eraqDlg.alert("尚未登录浙里办或登录信息已过期");

        //检测是否为微信登录
        /*const sUserAgent = window.navigator.userAgent.toLowerCase();
        if (sUserAgent.includes('miniprogram/wx') || window.__wxjs_environment === 'miniprogram') {
            let ticketId = strUtils.getUrlParam("ticketId");
            doSsoWxLogin(ticketId);
            return;
        }*/

        //支付宝小程序登录
        /*if (sUserAgent.indexOf('miniprogram') > -1 || sUserAgent.indexOf('alipay') > -1) {
            window.location.href = ssoAliUrl();
            return;
        }*/

        //检测浙里办平台用户登录类型
        /*ZWJSBridge.onReady(() => {
            ZWJSBridge.getUserType().then((result) => {
                console.log(result);
                window.location.href = ((parseInt(result.userType,10) === 2) ? ssoFrUrl() : ssoGrUrl());
            }).catch(() => {
                showErr("检测当前用户类型异常，请返回浙里办重新登录");
            });
        });*/
    },
}
export default ssoUtil;

